package com.sx.baseproject.framework.tools.pay;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.webkit.CookieManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;

import com.sx.widget.app.dialog.BaseDialog;
import com.sx.widget.app.dialog.WaitDialog;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;

public class H5PayActivity extends Activity {
    private BaseDialog waitingDialog;

    protected void showDialog() {
        Observable.just("")
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String s) {
                        try {
                            waitingDialog= new WaitDialog.Builder(H5PayActivity.this)
                                    .setMessage("正在打开支付宝")
                                    .addOnDismissListener(new BaseDialog.OnDismissListener() {
                                        @Override
                                        public void onDismiss(BaseDialog dialog) {
                                            finish();
                                        }
                                    })
                                    .show();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    protected void dimissDialog() {
        Observable.just("")
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String s) {
                        try {
                            if (waitingDialog != null) {
                                if (waitingDialog.isShowing()) {
                                    waitingDialog.dismiss();
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private WebView mWebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        showDialog();
        Bundle extras = null;
        try {
            extras = getIntent().getExtras();
        } catch (Exception e) {
            finish();
            return;
        }
        if (extras == null) {
            finish();
            return;
        }
        String url = null;
        try {
            url = extras.getString("url");
        } catch (Exception e) {
            finish();
            return;
        }
        if (TextUtils.isEmpty(url)) {
            // 测试H5支付，必须设置要打开的url网站
            new AlertDialog.Builder(H5PayActivity.this).setTitle("Error")
                    .setMessage("Missing URL to load. Please configure in PayDemoActivity.h5Pay()")
                    .setPositiveButton("确定", new OnClickListener() {

                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {
                            finish();
                        }
                    }).show();

        }
        super.requestWindowFeature(Window.FEATURE_NO_TITLE);
        LinearLayout layout = new LinearLayout(getApplicationContext());
        LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        layout.setOrientation(LinearLayout.VERTICAL);
        setContentView(layout, params);
        mWebView = new WebView(getApplicationContext());
        params.weight = 1;
        mWebView.setVisibility(View.VISIBLE);
        layout.addView(mWebView, params);

        WebSettings settings = mWebView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);

        // 启用二方/三方 Cookie 存储和 DOM Storage
        // 注意：若要在实际 App 中使用，请先了解相关设置项细节。
        CookieManager.getInstance().setAcceptCookie(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            CookieManager.getInstance().setAcceptThirdPartyCookies(mWebView, true);
        }
        settings.setDomStorageEnabled(true);
        settings.setJavaScriptEnabled(true);                       //可执行js
        settings.setDefaultZoom(WebSettings.ZoomDensity.MEDIUM);   //设置页面默认缩放密度
        settings.setDefaultTextEncodingName("UTF-8");              //设置默认的文本编码名称，以便在解码html页面时使用
        settings.setAllowContentAccess(true);                      //启动或禁用WebView内的内容URL访问
        settings.setAppCacheEnabled(false);                        //设置是否应该启用应用程序缓存api
        settings.setBuiltInZoomControls(false);                    //设置WebView是否应该使用其内置的缩放机制
        settings.setUseWideViewPort(true);                         //设置WebView是否应该支持viewport
        settings.setLoadWithOverviewMode(true);                    //不管WebView是否在概述模式中载入页面，将内容放大适合屏幕宽度
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);          //重写缓存的使用方式
        settings.setJavaScriptCanOpenWindowsAutomatically(true);   //告知js自动打开窗口
        settings.setLoadsImagesAutomatically(true);                //设置WebView是否应该载入图像资源
        settings.setAllowFileAccess(true);                         //启用或禁用WebView内的文件访问
        settings.setDomStorageEnabled(true);
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.startsWith("weixin://wap/pay?")) {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(url));
                    startActivity(intent);

                    return true;
                }
                if (url.startsWith("alipays:") || url.startsWith("alipay")) {
                    try {
                        Uri parse = Uri.parse(url);
                        startActivity(new Intent("android.intent.action.VIEW",parse ));
                    } catch (Exception e) {
                        new AlertDialog.Builder(H5PayActivity.this)
                                .setMessage("未检测到支付宝客户端，请安装后重试。")
                                .setPositiveButton("立即安装", new OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        Uri alipayUrl = Uri.parse("https://d.alipay.com");
                                        startActivity(new Intent("android.intent.action.VIEW", alipayUrl));
                                    }
                                }).setNegativeButton("取消", null).show();
                    } finally {
                        dimissDialog();
                        finish();
                    }
                    return true;
                }
                if (!(url.startsWith("http") || url.startsWith("https"))) {
                    return true;
                }
                view.loadUrl(url);
                return true;
            }
        });

        mWebView.loadUrl(url);
        mWebView.setVisibility(View.GONE);

        // 启用 WebView 调试模式。
        // 注意：请勿在实际 App 中打开！
//		WebView.setWebContentsDebuggingEnabled(true);
    }

    @Override
    public void onBackPressed() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            finish();
        }
    }

    @Override
    public void finish() {
        super.finish();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mWebView != null) {
            mWebView.removeAllViews();
            try {
                mWebView.destroy();
            } catch (Throwable t) {
            }
            mWebView = null;
        }
    }
}
